<?php
defined('IN_TS') or die('Access Denied.');

$title = '待回答问题';

//用户关注的分类
if (isset($TS_USER['userid']) && '' != $TS_USER['userid'])
{
	$userid = intval($TS_USER['userid']);
	$selectedcate = $new['ask']->findAll('ask_user_cate', array('userid'=>$userid));
}

//分页处理
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$start = ASK_PAGE_NUM * ($page - 1);

//前20条 两小时内没人回答 或者答案数为0的
$two_hour_time = time() - 7200;
$sql = "select askid,userid,title,content,count,pid,action,addtime from ".dbprefix."ask_topic where `addtime` > '".$two_hour_time."' and `isaudit`='0' or `count` = '0' and `isaudit`='0' order by addtime desc";
$askarr = $new['ask']->db->fetch_all_assoc($sql." limit $start,".ASK_PAGE_NUM);
//总数
$askNum = $new['ask']->db->once_num_rows($sql);

foreach ($askarr as $key=>$v)
{
	$selectsql = "select a.cateid,b.catename from ".dbprefix."ask_topic_cate a left join ".dbprefix."ask_cate b on a.cateid = b.cateid where askid=".$v['askid'];
	$askarr[$key]['cate'] = $new['ask']->db->fetch_all_assoc($selectsql);
	
	$actionarr = array();
	//最近的操作行为 目前有两种行为 回复和顶答案
	if ('ask_comment' == $v['action'])
	{
	    $actionarr = $new['ask']->find('ask_comment', array('commentid'=>$v['pid']), 'commentid, userid, comment, addtime');
	    $actionarr['addtime'] = getTime($actionarr['addtime'], time());

        $actionarr['comment'] =  cututf8(t(tsDecode($actionarr['comment'])), 0, 120);
	    $actionarr['user'] = aac('user')->getOneUser($actionarr['userid']);
	    $actionarr['action'] = 'ask_comment';
	}
	if ('ask_comment_op' == $v['action'])
	{
		$sql = "select a.commentid,a.userid,b.userid as cuserid,b.comment,a.updatetime,b.addtime,b.digg from ".dbprefix."ask_comment_op a left join ".dbprefix."ask_comment b on a.commentid = b.commentid where pid = ".$v['pid'];
		$actionarr = $new['ask']->db->once_fetch_assoc($sql);
		$actionarr['commenttime'] = date('Y-m-d H:i:s', $actionarr['addtime']);
		$actionarr['addtime'] = getTime($actionarr['updatetime'], time());

        $actionarr['comment'] = cututf8(t(tsDecode($actionarr['comment'])), 0, 120);
	    $actionarr['user'] = aac('user')->getOneUser($actionarr['userid']);
	    $actionarr['cuser'] = aac('user')->getOneUser($actionarr['cuserid']);
	    $actionarr['action'] = 'ask_comment_op';
	}
	//发布还没有操作行为
	if ('' == $v['action'])
	{
		$actionarr['user'] = aac('user')->getOneUser($askarr[$key]['userid']);
		$actionarr['addtime'] = getTime($askarr[$key]['addtime'], time());

        $askarr[$key]['content'] = cututf8(t(tsDecode($askarr[$key]['content'])), 0, 120);
	}
	$askarr[$key]['actionarr'] = $actionarr;
}

//问题分类
$arrCate = $new['ask']->findAll('ask_cate');

//分页 上一页和下一页
$pre = 0;
$next = 0;
if (($page-1)>0 && ($page-1)< ceil($askNum/ASK_PAGE_NUM))
{
	$pre = $page-1;
}

if (($page+1)<= ceil($askNum/ASK_PAGE_NUM))
{
	$next = $page+1;
}
$url = tsUrl('ask', 'latest', array('page'=>''));

include template('index');